<template>
  <div class="software-selection">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">
        <el-icon>
          <Box />
        </el-icon>
        软件选择
      </h1>
      <p class="page-description">选择您需要的开发工具，构建专属的开发环境</p>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：软件列表 -->
      <el-col :xs="24" :md="16">
        <el-card class="software-list-card">
          <!-- 搜索和筛选 -->
          <div class="search-filters">
            <el-row :gutter="16">
              <el-col :xs="24" :sm="8">
                <el-input v-model="searchKeyword" placeholder="搜索软件名称、描述..." clearable @input="handleSearch">
                  <template #prefix>
                    <el-icon>
                      <Search />
                    </el-icon>
                  </template>
                </el-input>
              </el-col>
              <el-col :xs="8" :sm="4">
                <el-select v-model="selectedCategory" placeholder="分类" clearable @change="handleCategoryChange">
                  <el-option label="全部分类" value="" />
                  <el-option v-for="category in categories" :key="category" :label="category" :value="category" />
                </el-select>
              </el-col>
              <el-col :xs="8" :sm="4">
                <el-select v-model="selectedOs" placeholder="系统" @change="handleOsChange">
                  <el-option label="Windows" value="windows" />
                  <el-option label="Linux" value="linux" />
                  <el-option label="macOS" value="macos" />
                </el-select>
              </el-col>
              <el-col :xs="8" :sm="8">
                <div class="batch-actions">
                  <el-dropdown @command="handleBatchAction" trigger="click">
                    <el-button type="primary" :disabled="filteredSoftware.length === 0">
                      批量操作
                      <el-icon class="el-icon--right">
                        <ArrowDown />
                      </el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="selectAll">全选当前页</el-dropdown-item>
                        <el-dropdown-item command="selectNone">取消全选</el-dropdown-item>
                        <el-dropdown-item command="selectByCategory" divided>按分类选择</el-dropdown-item>
                        <el-dropdown-item command="selectCommon">选择常用软件</el-dropdown-item>
                        <el-dropdown-item command="selectDevelopment">开发环境套装</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </el-col>
            </el-row>

            <!-- 快速分类标签 -->
            <div class="category-tags" v-if="popularCategories.length > 0">
              <span class="tags-label">热门分类：</span>
              <el-tag v-for="category in popularCategories" :key="category"
                :type="selectedCategory === category ? 'primary' : ''"
                :effect="selectedCategory === category ? 'dark' : 'plain'" @click="handleCategoryTag(category)"
                class="category-tag" size="small">
                {{ category }}
              </el-tag>
            </div>

            <!-- 统计信息 -->
            <div class="stats-info">
              <el-text type="info" size="small">
                共找到 {{ filteredSoftware.length }} 个软件，已选择 {{ selectedCount }} 个
              </el-text>
            </div>
          </div>

          <!-- 软件列表 -->
          <div class="software-list" v-loading="loading">
            <div v-for="software in filteredSoftware" :key="software.id" class="software-item"
              :class="{ selected: isSelected(software.id) }" @click="toggleSoftware(software)">
              <div class="software-icon">
                <div class="software-icon-wrapper">
                  <img v-if="getSoftwareIcon(software.name)" :src="getSoftwareIcon(software.name)"
                    :alt="software.displayName || software.name" class="software-icon-img"
                    @error="handleIconError($event, software.name)" />
                  <el-avatar v-else :size="50" shape="square">
                    {{ (software.displayName || software.name || '?').charAt(0) }}
                  </el-avatar>
                </div>
              </div>

              <div class="software-info">
                <div class="software-header">
                  <h3 class="software-name">{{ software.displayName }}</h3>
                  <div class="software-tags">
                    <el-tag :type="getCategoryType(software.category)" size="small">
                      {{ software.category }}
                    </el-tag>
                    <el-tag v-if="isPopularSoftware(software.name)" type="warning" size="small">
                      热门
                    </el-tag>
                  </div>
                </div>
                <p class="software-description">{{ software.description }}</p>
                <div class="software-meta">
                  <div class="meta-item">
                    <el-icon>
                      <Download />
                    </el-icon>
                    <span>最新版本: {{ software.latestVersion?.version || 'N/A' }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon>
                      <Monitor />
                    </el-icon>
                    <span>支持: {{ formatOsSupport(software.osSupport) }}</span>
                  </div>
                  <div class="meta-item" v-if="software.latestVersion?.fileSize">
                    <el-icon>
                      <Document />
                    </el-icon>
                    <span>大小: {{ formatFileSize(software.latestVersion.fileSize) }}</span>
                  </div>
                </div>
              </div>

              <div class="software-actions">
                <el-button v-if="!isSelected(software.id)" type="primary" size="small"
                  @click.stop="addSoftware(software)">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  添加
                </el-button>
                <el-button v-else type="success" size="small" @click.stop="removeSoftware(software.id)">
                  <el-icon>
                    <Check />
                  </el-icon>
                  已选
                </el-button>
              </div>
            </div>

            <!-- 空状态 -->
            <el-empty v-if="!loading && filteredSoftware.length === 0" description="没有找到匹配的软件" :image-size="100">
              <el-button type="primary" @click="clearFilters">清除筛选条件</el-button>
            </el-empty>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：已选择的软件 -->
      <el-col :xs="24" :md="8">
        <el-card class="selected-software-card" :body-style="{ padding: '20px' }">
          <template #header>
            <div class="card-header">
              <span>已选择的软件 ({{ selectedCount }})</span>
              <el-button v-if="selectedCount > 0" type="text" size="small" @click="clearSelected">
                清空
              </el-button>
            </div>
          </template>

          <div v-if="selectedCount === 0" class="empty-selection">
            <el-icon size="48" color="#c0c4cc">
              <Box />
            </el-icon>
            <p>还没有选择任何软件</p>
            <p class="hint">点击左侧软件列表中的软件来添加</p>
          </div>

          <div v-else class="selected-list">
            <div v-for="software in selectedSoftware" :key="software.id" class="selected-item">
              <div class="selected-info">
                <div class="selected-header">
                  <div class="selected-name">{{ software.displayName }}</div>
                  <el-tag :type="getCategoryType(software.category)" size="small">
                    {{ software.category }}
                  </el-tag>
                </div>
                <el-select v-model="software.version" size="small" @change="updateVersion(software.id, $event)"
                  @focus="loadSoftwareVersions(software.id)">
                  <el-option label="最新版本" value="latest" />
                  <el-option v-for="version in getSoftwareVersions(software.id)" :key="version.version"
                    :label="`${version.version}${version.isLatest ? ' (最新)' : ''}`" :value="version.version" />
                </el-select>
              </div>
              <el-button type="text" size="small" @click="removeSoftware(software.id)">
                <el-icon>
                  <Close />
                </el-icon>
              </el-button>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="selection-actions" v-if="selectedCount > 0">
            <el-button type="primary" @click="goToScript" :disabled="selectedCount === 0">
              生成脚本
              <el-icon class="el-icon--right">
                <ArrowRight />
              </el-icon>
            </el-button>
            <el-button @click="saveAsTemplate">
              {{ saveButtonText }}
            </el-button>
          </div>
        </el-card>

        <!-- 安装路径设置 -->
        <el-card class="install-path-card">
          <template #header>
            <span>安装路径设置</span>
          </template>
          <el-input v-model="installPath" placeholder="请输入安装路径" @change="updateInstallPath">
            <template #prepend>路径</template>
          </el-input>
          <div class="path-hints">
            <el-tag size="small" type="info">Windows: C:\DevEnv</el-tag>
            <el-tag size="small" type="info">Linux: /opt/devenv</el-tag>
            <el-tag size="small" type="info">macOS: /Applications/DevEnv</el-tag>
          </div>
        </el-card>
      </el-col>
    </el-row>


  </div>
</template>

<script setup>
import api from '@/utils/api'
import
{
  ArrowRight,
  Box,
  Check,
  Close,
  Document,
  Download, Monitor,
  Plus,
  Search
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onErrorCaptured, onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useSoftwareStore } from '../stores/software'
import { useUserStore } from '../stores/user'

const router = useRouter()
const softwareStore = useSoftwareStore()
const userStore = useUserStore()

// 软件版本管理
const softwareVersionsCache = ref(new Map()) // 缓存软件版本列表
const loadingVersions = ref(new Set()) // 正在加载版本的软件ID集合

// 响应式数据 - 从store获取状态
const searchKeyword = computed({
  get: () => softwareStore.searchKeyword,
  set: (value) => softwareStore.setSearchKeyword(value)
})

const selectedCategory = computed({
  get: () => softwareStore.selectedCategory,
  set: (value) => softwareStore.setSelectedCategory(value)
})

const selectedOs = computed({
  get: () => softwareStore.selectedOs,
  set: (value) => softwareStore.setSelectedOs(value)
})

// 计算属性
const filteredSoftware = computed(() => softwareStore.filteredSoftware)
const selectedSoftware = computed(() => softwareStore.selectedSoftware)
const selectedCount = computed(() => softwareStore.selectedCount)
const categories = computed(() => softwareStore.categories)
const loading = computed(() => softwareStore.loading)
const installPath = computed(() => softwareStore.installPath)

// 热门分类
const popularCategories = computed(() =>
{
  return ['Runtime', 'IDE', 'Database', 'Tool', 'Build Tool']
})

// 常用软件列表
const commonSoftware = ['jdk', 'nodejs', 'python', 'git', 'vscode', 'mysql']

// 检查是否从模板管理页面跳转过来
const isFromTemplateManagement = computed(() =>
{
  return sessionStorage.getItem('templateFormState') !== null
})

// 动态按钮文本
const saveButtonText = computed(() =>
{
  return isFromTemplateManagement.value ? '确认选择' : '保存为模板'
})

// 生命周期
onMounted(async () =>
{
  console.log('SoftwareSelection: onMounted开始')
  console.log('SoftwareSelection: 当前软件列表长度:', softwareStore.softwareList.length)

  try
  {
    // 如果store中没有数据，则加载
    if (softwareStore.softwareList.length === 0)
    {
      console.log('SoftwareSelection: 软件列表为空，开始加载数据...')
      await Promise.all([
        softwareStore.fetchSoftwareList(),
        softwareStore.fetchCategories()
      ])
      console.log('SoftwareSelection: 数据加载完成')
      console.log('SoftwareSelection: 软件列表长度:', softwareStore.softwareList.length)
      console.log('SoftwareSelection: 分类数量:', softwareStore.categories.length)
    } else
    {
      console.log('SoftwareSelection: 使用缓存数据')
    }

    // 确保初始状态正确
    if (!softwareStore.selectedOs)
    {
      console.log('SoftwareSelection: 设置默认操作系统为Windows')
      softwareStore.setSelectedOs('windows')
    }

    console.log('SoftwareSelection: 当前状态:', {
      loading: softwareStore.loading,
      softwareCount: softwareStore.softwareList.length,
      filteredCount: filteredSoftware.value.length,
      categories: softwareStore.categories,
      selectedOs: softwareStore.selectedOs
    })
  } catch (error)
  {
    console.error('SoftwareSelection: 加载失败:', error)
    ElMessage.error('加载软件列表失败: ' + error.message)
  }
})

// 组件卸载时清理资源
onUnmounted(() =>
{
  // 清理搜索防抖定时器
  if (handleSearch.timer)
  {
    clearTimeout(handleSearch.timer)
    handleSearch.timer = null
  }
})

// 错误捕获
onErrorCaptured((error, _instance, errorInfo) =>
{
  console.error('SoftwareSelection组件错误:', error, errorInfo)
  ElMessage.error('页面出现错误，请刷新重试')
  return false // 阻止错误继续传播
})

// 方法
const handleSearch = (keyword) =>
{
  // 状态已通过computed属性自动同步到store
  // 防抖处理，避免频繁搜索
  if (handleSearch.timer)
  {
    clearTimeout(handleSearch.timer)
  }

  handleSearch.timer = setTimeout(() =>
  {
    if (keyword && keyword.trim())
    {
      softwareStore.searchSoftware(keyword.trim())
    } else
    {
      softwareStore.fetchSoftwareList()
    }
  }, 300)
}

const handleCategoryChange = () =>
{
  // 状态已通过computed属性自动同步到store
  softwareStore.fetchSoftwareList()
}

const handleOsChange = () =>
{
  // 状态已通过computed属性自动同步到store
  softwareStore.fetchSoftwareList()
}

const isSelected = (softwareId) =>
{
  return selectedSoftware.value.some(item => item.id === softwareId)
}

const toggleSoftware = async (software) =>
{
  if (isSelected(software.id))
  {
    softwareStore.removeSoftware(software.id)
    ElMessage.success(`已移除 ${software.displayName}`)

    // 记录软件选择活动
    try
    {
      console.log('准备记录软件选择活动: 移除', software.displayName || software.name)
      await userStore.recordSoftwareSelection(software.displayName || software.name, '移除')
      console.log('软件选择活动记录成功: 移除', software.displayName || software.name)
    } catch (error)
    {
      console.warn('记录软件选择活动失败:', error)
    }
  } else
  {
    softwareStore.addSoftware(software)
    ElMessage.success(`已添加 ${software.displayName}`)

    // 记录软件选择活动
    try
    {
      console.log('准备记录软件选择活动: 添加', software.displayName || software.name)
      await userStore.recordSoftwareSelection(software.displayName || software.name, '添加')
      console.log('软件选择活动记录成功: 添加', software.displayName || software.name)
    } catch (error)
    {
      console.warn('记录软件选择活动失败:', error)
    }
  }
}

const addSoftware = async (software) =>
{
  softwareStore.addSoftware(software)
  ElMessage.success(`已添加 ${software.displayName}`)

  // 记录软件选择活动
  try
  {
    console.log('准备记录软件选择活动: 添加', software.displayName || software.name)
    await userStore.recordSoftwareSelection(software.displayName || software.name, '添加')
    console.log('软件选择活动记录成功: 添加', software.displayName || software.name)
  } catch (error)
  {
    console.warn('记录软件选择活动失败:', error)
  }
}

const removeSoftware = async (softwareId) =>
{
  const software = selectedSoftware.value.find(item => item.id === softwareId)
  softwareStore.removeSoftware(softwareId)
  ElMessage.success(`已移除 ${software?.displayName}`)

  // 记录软件选择活动
  if (software)
  {
    try
    {
      console.log('准备记录软件选择活动: 移除', software.displayName || software.name)
      await userStore.recordSoftwareSelection(software.displayName || software.name, '移除')
      console.log('软件选择活动记录成功: 移除', software.displayName || software.name)
    } catch (error)
    {
      console.warn('记录软件选择活动失败:', error)
    }
  }
}

// 批量操作
const handleBatchAction = async (command) =>
{
  switch (command)
  {
    case 'selectAll':
      const newlySelected = []
      filteredSoftware.value.forEach(software =>
      {
        if (!isSelected(software.id))
        {
          softwareStore.addSoftware(software)
          newlySelected.push(software)
        }
      })
      ElMessage.success(`已选择当前页面的 ${filteredSoftware.value.length} 个软件`)

      // 记录批量选择活动
      if (newlySelected.length > 0)
      {
        try
        {
          await userStore.recordSoftwareSelection(`批量选择${newlySelected.length}个软件`, '批量添加')
        } catch (error)
        {
          console.warn('记录批量选择活动失败:', error)
        }
      }
      break

    case 'selectNone':
      const removedCount = selectedSoftware.value.length
      softwareStore.clearSelectedSoftware()
      ElMessage.success('已取消所有选择')

      // 记录取消所有选择活动
      if (removedCount > 0)
      {
        try
        {
          await userStore.recordSoftwareSelection(`清空所有已选软件(${removedCount}个)`, '批量移除')
        } catch (error)
        {
          console.warn('记录取消选择活动失败:', error)
        }
      }
      break

    case 'selectByCategory':
      if (selectedCategory.value)
      {
        const categorySoftware = filteredSoftware.value.filter(s => s.category === selectedCategory.value)
        const newlySelectedByCategory = []
        categorySoftware.forEach(software =>
        {
          if (!isSelected(software.id))
          {
            softwareStore.addSoftware(software)
            newlySelectedByCategory.push(software)
          }
        })
        ElMessage.success(`已选择 ${selectedCategory.value} 分类的 ${categorySoftware.length} 个软件`)

        // 记录按分类选择活动
        if (newlySelectedByCategory.length > 0)
        {
          try
          {
            await userStore.recordSoftwareSelection(`${selectedCategory.value}分类软件(${newlySelectedByCategory.length}个)`, '按分类添加')
          } catch (error)
          {
            console.warn('记录按分类选择活动失败:', error)
          }
        }
      } else
      {
        ElMessage.warning('请先选择一个分类')
      }
      break

    case 'selectCommon':
      const commonSoftwareList = filteredSoftware.value.filter(s => commonSoftware.includes(s.name))
      const newlySelectedCommon = []
      commonSoftwareList.forEach(software =>
      {
        if (!isSelected(software.id))
        {
          softwareStore.addSoftware(software)
          newlySelectedCommon.push(software)
        }
      })
      ElMessage.success(`已选择 ${commonSoftwareList.length} 个常用软件`)

      // 记录常用软件选择活动
      if (newlySelectedCommon.length > 0)
      {
        try
        {
          await userStore.recordSoftwareSelection(`常用软件(${newlySelectedCommon.length}个)`, '批量添加')
        } catch (error)
        {
          console.warn('记录常用软件选择活动失败:', error)
        }
      }
      break

    case 'selectDevelopment':
      // 显示开发环境套装选择对话框
      showDevelopmentSuiteDialog()
      break
  }
}

// 分类标签点击
const handleCategoryTag = (category) =>
{
  if (selectedCategory.value === category)
  {
    selectedCategory.value = ''
  } else
  {
    selectedCategory.value = category
  }
  softwareStore.fetchSoftwareList()
}

// 清除筛选条件
const clearFilters = () =>
{
  searchKeyword.value = ''
  selectedCategory.value = ''
  softwareStore.fetchSoftwareList()
}

const updateVersion = (softwareId, version) =>
{
  softwareStore.updateSoftwareVersion(softwareId, version)
}

// 版本管理方法
const loadSoftwareVersions = async (softwareId) =>
{
  // 如果已经有缓存或正在加载，则不重复加载
  if (softwareVersionsCache.value.has(softwareId) || loadingVersions.value.has(softwareId))
  {
    return
  }

  loadingVersions.value.add(softwareId)

  try
  {
    const response = await api.get(`/software/${softwareId}/versions`)
    if (response.code === 200 && response.data)
    {
      softwareVersionsCache.value.set(softwareId, response.data)
    }
  } catch (error)
  {
    console.warn(`加载软件 ${softwareId} 的版本列表失败:`, error)
  } finally
  {
    loadingVersions.value.delete(softwareId)
  }
}

const getSoftwareVersions = (softwareId) =>
{
  return softwareVersionsCache.value.get(softwareId) || []
}

const clearSelected = () =>
{
  softwareStore.clearSelectedSoftware()
  ElMessage.success('已清空选择')
}

const updateInstallPath = (path) =>
{
  // 验证路径格式
  if (path && typeof path === 'string')
  {
    const trimmedPath = path.trim()
    if (trimmedPath)
    {
      softwareStore.setInstallPath(trimmedPath)
    }
  }
}



const goToScript = () =>
{
  router.push('/script')
}

const saveAsTemplate = () =>
{
  if (selectedCount.value === 0)
  {
    ElMessage.warning('请至少选择一个软件')
    return
  }

  // 检查是否是从模板管理页面跳转过来的
  const formState = sessionStorage.getItem('templateFormState')

  if (formState)
  {
    // 如果是从模板管理页面跳转过来的，直接返回到模板管理页面
    router.push('/templates')
  } else
  {
    // 否则，将当前选择的软件数据存储到sessionStorage，供模板管理页面使用
    const templateData = {
      softwareList: selectedSoftware.value.map(software => ({
        id: software.id,
        name: software.name,
        displayName: software.displayName,
        version: software.version,
        category: software.category
      })),
      autoCreate: true // 标记需要自动打开创建模板弹窗
    }

    sessionStorage.setItem('pendingTemplateData', JSON.stringify(templateData))

    // 跳转到我的模板页面
    router.push('/templates')
  }
}

const getCategoryType = (category) =>
{
  const typeMap = {
    'IDE': 'primary',
    'Runtime': 'success',
    'Database': 'warning',
    'Tool': 'info',
    'Build Tool': 'danger'
  }
  return typeMap[category] || 'info'
}

const formatOsSupport = (osSupport) =>
{
  // 安全检查：如果osSupport为空，返回默认值
  if (!osSupport || osSupport === null)
  {
    return '全平台'
  }

  return osSupport.split(',').map(os =>
  {
    const osMap = {
      'windows': 'Win',
      'linux': 'Linux',
      'macos': 'Mac'
    }
    return osMap[os.trim()] || os
  }).join(', ')
}

// 格式化文件大小
const formatFileSize = (bytes) =>
{
  if (!bytes) return 'N/A'
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
}

// 获取软件图标
const getSoftwareIcon = (softwareName) =>
{
  // 安全检查：如果softwareName为空，返回null
  if (!softwareName || softwareName === null)
  {
    return null
  }

  const iconMap = {
    // 编程语言和运行时
    'java': '/java.svg',
    'node.js': '/nodejs.svg',
    'python': '/python.svg',
    'golang': '/golang.svg',
    'go': '/GO.svg',
    'rust': '/rust.svg',
    'php': '/php.svg',
    'ruby': '/ruby.svg',
    'dotnet': '/dotnet.svg',
    'cpp': '/cpp.svg',

    // 开发工具和IDE
    'git': '/git.svg',
    'github': '/github.svg',
    'visual studio code': '/vscode.svg',
    'intellij idea community': '/idea.svg',
    'intellij': '/idea.svg',
    'clion': '/clion.svg',
    'phpstorm': '/phpstorm.svg',
    'pycharm': '/pycharm.svg',
    'webstorm': '/webstorm.svg',
    'androidstudio': '/androidstudio.svg',
    'visualstudio': '/VisualStudio.svg',
    'vim': '/vim.svg',
    'emacs': '/emacs.svg',
    'sublime': '/sublime.svg',
    'atom': '/Atom.svg',
    'typora': '/Typora.svg',

    // 数据库
    'mysql': '/mysql.svg',
    'postgresql': '/postgresql.svg',
    'mongodb': '/mongodb.svg',
    'redis': '/redis.svg',
    'elasticsearch': '/elasticsearch.svg',
    'opengauss': '/openGauss.svg',
    'kafka': '/kafka.svg',
    'spark': '/spark.svg',

    // 构建工具和包管理
    'maven': '/maven.svg',
    'gradle': '/gradle.svg',
    'npm': '/npm.svg',
    'yarn': '/yarn.svg',
    'webpack': '/webpack.svg',
    'vite': '/vite.svg',

    // 服务器和容器
    'docker': '/docker.svg',
    'kubernetes': '/kubernetes.svg',
    'nginx': '/nginx.svg',
    'apache': '/apache.svg',

    // 浏览器
    'chrome': '/chrome.svg',
    'firefox': '/firefox.svg',

    // 开发运维工具
    'postman': '/postman.svg',
    'jenkins': '/jenkins.svg',
    'terraform': '/Terraform.svg',
    'ansible': '/ansible.svg',

    // Adobe 套件
    'photoshop': '/adobe-photoshop.svg',
    'illustrator': '/adobe-illustrator.svg',
    'aftereffects': '/adobe-after-effects.svg',
    'animate': '/adobe-animate.svg',
    'audition': '/adobe-audition.svg',
    'bridge': '/adobe-bridge.svg',
    'dreamweaver': '/adobe-dreamweaver.svg',
    'fireworks': '/adobe-fireworks.svg',
    'flash': '/adobe-flash.svg',
    'framemaker': '/adobe-framemaker.svg',
    'indesign': '/adobe-indesign.svg',
    'lightroom': '/adobe-lightroom.svg'
  }
  return iconMap[softwareName.toLowerCase()] || null
}

// 处理图标加载错误
const handleIconError = (event, softwareName) =>
{
  console.warn(`图标加载失败: ${softwareName}`)
  // 隐藏失败的图片，让 el-avatar 显示
  event.target.style.display = 'none'
}

// 判断是否为热门软件
const isPopularSoftware = (softwareName) =>
{
  // 安全检查：如果softwareName为空，返回false
  if (!softwareName || softwareName === null)
  {
    return false
  }
  return commonSoftware.includes(softwareName)
}

// 显示开发环境套装选择对话框
const showDevelopmentSuiteDialog = () =>
{
  ElMessageBox.confirm(
    '请选择要安装的开发环境套装：',
    '开发环境套装',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
      customClass: 'development-suite-dialog'
    }
  ).then(() =>
  {
    // 这里可以实现套装选择逻辑
    ElMessage.info('开发环境套装功能开发中...')
  }).catch(() =>
  {
    // 用户取消
  })
}
</script>

<style scoped>
.software-selection {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.page-description {
  color: #7f8c8d;
  font-size: 16px;
}

.search-filters {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.category-tags {
  margin-top: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.tags-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.category-tag {
  cursor: pointer;
  transition: all 0.3s ease;
}

.category-tag:hover {
  transform: translateY(-1px);
}

.stats-info {
  margin-top: 12px;
  text-align: right;
}

.batch-actions {
  display: flex;
  justify-content: flex-end;
}

.software-list {
  max-height: 600px;
  overflow-y: auto;
}

.software-item {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  margin-bottom: 12px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  gap: 12px;
}

.software-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
  transform: translateY(-1px);
}

.software-item.selected {
  border-color: #67c23a;
  background-color: #f0f9ff;
}

.software-icon {
  flex-shrink: 0;
}

.software-icon-wrapper {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.software-icon-svg {
  width: 40px;
  height: 40px;
  font-size: 40px;
}

.software-icon-img {
  width: 40px;
  height: 40px;
  object-fit: contain;
  border-radius: 4px;
}

.software-info {
  flex: 1;
  min-width: 0;
}

.software-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 8px;
  gap: 12px;
}

.software-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
  line-height: 1.4;
}

.software-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  flex-shrink: 0;
}

.software-description {
  color: #7f8c8d;
  font-size: 14px;
  line-height: 1.5;
  margin: 8px 0 12px 0;
}

.software-meta {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #909399;
}

.meta-item .el-icon {
  font-size: 14px;
}

.software-actions {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.selected-software-card {
  position: sticky;
  top: 20px;
  z-index: 10;
  margin-bottom: 16px;
  background: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.empty-selection {
  text-align: center;
  padding: 40px 20px;
  color: #7f8c8d;
}

.empty-selection .hint {
  font-size: 12px;
  margin-top: 8px;
}

.selected-list {
  max-height: 300px;
  overflow-y: auto;
}

.selected-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border-radius: 6px;
}

.selected-info {
  flex: 1;
}

.selected-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
  gap: 8px;
}

.selected-name {
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
  flex: 1;
}

.selection-actions {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.install-path-card {
  position: relative;
  z-index: 5;
}

.install-path-card .path-hints {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-title {
    font-size: 24px;
  }

  .software-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .software-actions {
    margin-left: 0;
    margin-top: 12px;
    align-self: flex-end;
  }

  .software-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

/* 创建模板对话框样式 */
.form-hint {
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}

.selected-software-preview {
  min-height: 60px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.software-count {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
